//
//  TextView-Extension.swift
//  Emotion
//
//  Created by maker on 2016/11/23.
//  Copyright © 2016年 maker. All rights reserved.
//

import UIKit

extension UITextView {

    //MARK:==========textView 插入表情==========
    func insertEmotion( _ emotion : EmotionModel) {
        if emotion.isEmpty {
            return
        }
        if emotion.isDelete {
            deleteBackward()
            return
        }
        if emotion.codeString != nil {
            let textRange = selectedTextRange!
            replace(textRange, withText: emotion.codeString!)
            return
        }
        
        //普通表情
        //1.获取到原来的属性字符串
        let mutableAttr = NSMutableAttributedString(attributedString: attributedText)
        
        //2.创建当前表情的属性字符串
        let attach = EmotionAttachment()
        attach.image = UIImage(contentsOfFile: emotion.pngPath!)
        attach.chs = emotion.chs
        let attrImageStr = NSAttributedString(attachment: attach)
        //2.1设置图片大小
        let font = self.font!
        attach.bounds = CGRect(x: 0, y: -4, width: font.lineHeight + 2, height: font.lineHeight + 2)
        
        
        //3.插入表情属性字符串
        let range = selectedRange
        mutableAttr.replaceCharacters(in: range, with: attrImageStr)
        attributedText = mutableAttr
        
        //4.处理两个小 bug
        self.font = font //把字体大小赋值回去.防止其字体变小
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }


    //MARK:==========获取 textView 的表情字符串==========
    func getEmotionStr() -> String {
        //1.用文本框的内容构建一个可变属性字符串
        let mutablAttrStr = NSMutableAttributedString(attributedString: attributedText)
        
        //2.遍历字典
        let range = NSRange(location: 0, length: mutablAttrStr.length)
        
        mutablAttrStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            if let attachment = dict["NSAttachment"] as? EmotionAttachment {
                //说明是表情
                mutablAttrStr.replaceCharacters(in: range, with: NSAttributedString(string:attachment.chs! ))
            }
        }
        return mutablAttrStr.string
    }
    
    
    
}
